package com.parkLot.spring.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.mingke.Domain.BillEntity;
import com.mingke.Utils.PageUtils;
import com.mingke.Utils.R;
import com.mingke.ViewObject.BillInfoViewObject;
import com.mingke.ViewObject.HtmlStr;
import com.mingke.ViewObject.PayAsyncVo;
import com.mingke.ViewObject.PayVo;
import com.parkLot.spring.service.BillService;

import com.parkLot.spring.third.AliPayUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Size;


/**
 * 
 *
 * @author mingke
 * @email 1510181330@qq.com
 * @date 2021-02-16 11:28:40
 * 帐单状态的对应关系
 * 101 ： 未付款
 * 102 ： 已付款
 * 103 ： 停车中
 */
@Slf4j
@RestController
@RequestMapping("/bill")
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private AliPayUtils aliPayUtils;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = billService.queryPage(params);

        return R.ok().put("page", page);
    }

    @GetMapping("/getBillListByUid")
    public R List(@RequestParam("id") Integer id){
        if(id == null || id <= 0){
            return R.error("重新登录");
        }else {
            List<BillInfoViewObject> list = billService.getBillListByUid(id);
            return R.ok().put("data", list);
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{billId}")
    public R info(@PathVariable("billId") Integer billId){
		BillEntity bill = billService.getById(billId);

        return R.ok().put("bill", bill);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody BillEntity bill){
		billService.save(bill);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BillEntity bill){
		billService.updateById(bill);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] billIds){
		billService.removeByIds(Arrays.asList(billIds));

        return R.ok();
    }

    @GetMapping("/getPointsByUser")
    public R getPointsByUser(){
        return R.ok();
    }

    /*
    @ResponseBody
    @PostMapping(value="/payBillByVo", produces = "text/html")
    public String payBillByVo(@RequestBody PayVo vo) throws AlipayApiException {
        String result = aliPayUtils.pay(vo);
        //System.out.println(result);
        return result;
    }*/
    @PostMapping(value="/payBillByVo")
    public R payBillByVo(@RequestBody PayVo vo) throws AlipayApiException {
        String result = aliPayUtils.pay(vo);

        return R.ok().put("result", result);
    }

    @GetMapping("/syncMethod")
    public String syncMethod(){
        log.info("支付宝同步通知：");
        return "hello, syncMethod";
    }

    @PostMapping("/asyncMethod")
    public String asyncMethod(PayAsyncVo vo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        log.info("支付宝异步通知："+vo.toString());
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, aliPayUtils.alipay_public_key, aliPayUtils.getCharset(), aliPayUtils.getSign_type());
        if(verify_result){
            log.info("验证成功");
            if(trade_status.equals("TRADE_FINISHED")){
                log.info("订单完成");
            }
            if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                BillEntity billEntity = billService.getById(vo.getOut_trade_no());
                if(Math.abs(Double.parseDouble(vo.getReceipt_amount())-billEntity.getBillFee())<1.0){
                    log.info("订单成功");
                    //修改订单状态为已付款
                    billEntity.setBillStatu(102);
                    billService.updateById(billEntity);
                }
            }
            return "success";
        }
        return "thanks, asyncMethod";
    }
}
